package initialize

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
	"go.uber.org/zap"
	"log"
	"os"
	"sale_system/goods_srv/global"
	"sale_system/goods_srv/model"
)

// 初始化es
func InitES() {

	host := fmt.Sprintf("http://%s:%d", global.ServerConfig.ESInfo.Host, global.ServerConfig.ESInfo.Port)
	logger := log.New(os.Stdout, "sale_system", log.LstdFlags)

	var err error
	global.ES, err = elastic.NewClient(elastic.SetURL(host), elastic.SetSniff(false), elastic.SetTraceLog(logger))
	if err != nil {
		zap.S().Info("初始化ES失败")
		panic(err)
	}

	// 新建mapping和index
	exists, err := global.ES.IndexExists(model.EsGoods{}.GetIndexName()).Do(context.Background())
	if err != nil {
		panic(err)
	}
	if !exists { // 不存在这个index数据表
		_, err := global.ES.CreateIndex(model.EsGoods{}.GetIndexName()).BodyString(model.EsGoods{}.GetMapping()).Do(context.Background())
		if err != nil {
			panic(err)
		}
	}
}
